package com.ma.chapter6.ABA;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicMarkableReference;

import static com.ma.util.Sleeper.sleep;

@Slf4j(topic = "m.TestABAAtomicMarkableReference")
public class TestABAAtomicMarkableReference {
    public static void main(String[] args) {
        GarbageBag bag = new GarbageBag("装满了垃圾");
        Thread.currentThread().setName("主线程");
        //参数二 看作是一个标记，表示垃圾已经满了
        AtomicMarkableReference<GarbageBag> ref = new AtomicMarkableReference<>(bag, true);

        log.debug("主线程启动.....");
        GarbageBag prev = ref.getReference();
        log.debug(prev.toString());



        new Thread(() -> {
            //sleep(2);
            log.debug("清理线程启动....");
            bag.setDesc("空垃圾袋...");
            while(!ref.compareAndSet(bag,bag,true,false)){
                log.debug("没必要清理");
                break;
            }
            log.debug(bag.toString());

        }, "清理线程1").start();


        //new Thread(() -> {
        //    //sleep(2);
        //    log.debug("清理线程启动....");
        //    bag.setDesc("空垃圾袋...");
        //    while(!ref.compareAndSet(bag,bag,true,false)){
        //        log.debug("没必要清理");
        //        break;
        //    }
        //    log.debug(bag.toString());
        //
        //}, "清理线程2").start();

        sleep(1);
        log.debug("主线程想换一只新垃圾袋？");
        boolean isSuccess = ref.compareAndSet(bag, new GarbageBag("空垃圾袋"), true, false);
        log.debug("换了么？{}",isSuccess);
        log.debug(ref.getReference().toString());


    }
}

class GarbageBag {
    String desc;

    public GarbageBag(String desc) {
        this.desc = desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    @Override
    public String toString() {
        return "GarbageBag{" +
                "desc='" + desc + '\'' +
                '}';
    }
}
